package server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.eclipse.jetty.websocket.WebSocket;
import com.google.gson.Gson;

public class ChatSocket implements WebSocket{
	private static final List<String> players = new ArrayList<String>();
	static{
		players.add("Player1");
		players.add("Player2");
		players.add("Player3");
		players.add("Player4");
		players.add("Player5");
		players.add("Player6");
		players.add("Player7");
		players.add("Player8");
		players.add("Player9");
		players.add("Player0");
	}	
	private Outbound outbound;
	Timer timer; 
	public void onConnect(Outbound outbound) {
		this.outbound=outbound;
		timer=new Timer();
	}

	public void onDisconnect() {
		timer.cancel();
	}

	public void onMessage(final byte frame, String data) {
		if(data.indexOf("disconnect")>=0){
			outbound.disconnect();
		}else{
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					try{
						outbound.sendMessage(frame,getMyJsonTicker());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}, new Date(),5000);
		}
	}
	public String getMyJsonTicker(){
		Map<String, String> json = new LinkedHashMap<String, String>();
		int rnd = (int) (Math.random() * 10);
		int counter = 0;
		for (String player : players) {
			if (counter == rnd) {
				json.put("player", player);
				json.put("message", "Very Nice hand");
				break;
			} else if(counter == players.size()-1) {
				System.out.println("ERROR: chat failed with rnd : " + Integer.toString(rnd));
				json.put("player", player);
				json.put("message", "Very Nice hand");
			} else {
				counter++;
				continue;
			}		
		}
		String result = new Gson().toJson(json);
		return result;
	}	
	public void onMessage(byte arg0, byte[] arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub		
	}
	public void onFragment(boolean arg0, byte arg1, byte[] arg2, int arg3, int arg4) {
		// TODO Auto-generated method stub
	}
}
